import fs from "fs";
import path from "path";

const gloabl = {
    port: 3205,
    publicPath: path.join(__dirname, "public"),
    dataPath: path.join(__dirname, "data"),
}

export const imgBuilder = (resource,folder,callback) => {
    if(!resource) return "";
    let head_filename = Date.now() + '.png';
    const imgPath = path.join(gloabl.publicPath, `/image/${folder}/`) + head_filename;
    const base64 = resource.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64
    const dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象，
    fs.writeFile(imgPath, dataBuffer, function(err) { //用fs写入文件
        if (err) {
            console.log("err", err);
            callback(false);
        } else {
            console.log('写入成功！');
            callback(`/image/${folder}/${head_filename}`);
        }
    });
}
export const imgBuilderArr = (resourceArr,folder,callback,resArr)=>{
    let targetSrc = resourceArr.shift();
    if(targetSrc){
        imgBuilder(targetSrc,folder,res=>{
            resArr.push(res);
            imgBuilderArr(resourceArr,folder,callback,resArr);
        });
    }
    else callback(resArr);
}
export const imgBuilderArr2 = (resourceArr,folder,callback)=>{
    let resArr = [];
    imgBuilderArr(resourceArr,folder,callback,resArr);
}